<script setup>
import { reactive } from 'vue';
import { ElMessage } from 'element-plus';
import { Md5 } from 'ts-md5';
import { useRouter, useRoute } from 'vue-router';
import { iuserLogin, iuserInfo, projectApi, companyById, companyByIdItems, iuserPhonecode, iuserRepassword  } from '@T2/service/api.ts';
import { useIuserInfoStore, useIuserCompanyStore, useLocalMenusStore, useCurrentWatchStore } from '@T2/store/users.ts';
import { isPhone, getValidMenus } from '@T2/utils/utils.ts';
import { getToSomeProjectPath, getToCompanyPath  } from '@T2/utils/users.ts';
import Particles from './components/particles.vue';
import PicCode from './components/picCode.vue';
import SafetyIcon from '~icons/custom/safety'

const router = useRouter();
const route = useRoute();
const iuserInfoStore = useIuserInfoStore();
const iuserCompanyStore = useIuserCompanyStore();
const localMenusStore = useLocalMenusStore();
const currentWatchStore = useCurrentWatchStore();

const Resd = reactive({
  forget: route.query?.reset && true,
});

/* 登录账号部分 */
const loginResd = reactive({
  username: '',
  password: '',
  passwordType: true,
  code: '',
  compareCode: '',
  logining: false,
});
const compareCodeChange = (e) => {
  loginResd.code = '';
  loginResd.compareCode = e;
}
const loginClick = () => {
  if (!loginResd.username || !loginResd.password) {
    return ElMessage.error('请输入账号密码');
  } else if (!loginResd.code) {
    return ElMessage.error('请输入验证码');
  } else if (loginResd.compareCode.toLowerCase() !== loginResd.code.toLowerCase()) {
    return ElMessage.error('验证码错误');
  }
  actionLogin();
}
const actionLogin = () => {
  loginResd.logining = true;
  iuserLogin({
    method: 'post',
    data: {
      username: loginResd.username,
      password: Md5.hashStr('.ieieye.com' + loginResd.password + 'shhengji'),
    },
  }).then(res => {
    if (!res) {
      loginResd.logining = false;
    }
    getIuserInfo();
  }).catch(() => {
    loginResd.logining = false;
  });
}
const getIuserInfo = () => {
  iuserInfo({
    method: 'get',
  }).then(res => {
    if (!res) {
      loginResd.logining = false;
    }
    iuserInfoStore.setIuserInfo(res);
    getPListAndMenus(res);
  }).catch(() => {
    loginResd.logining = false;
  });
}
const getPListAndMenus = (iuser) => {
  Promise.all([getProjectList(iuser), getCompanyItems(iuser), getCompanyDetail(iuser)]).then(res => {
    const projectList = res[0], menusItem = res[1], companyDetail = res[2];
    
    iuserCompanyStore.setCompanyDetail(companyDetail);
    
    currentWatchStore.setProjectList(projectList);
    
    const isCoSuper = iuser.created_company === iuser.info.company;
    /* 筛选公司权限，包括移动端 */
    const CoMenus = getValidMenus(menusItem?.company?.children || [], isCoSuper, iuser.company_roles);
    /* 筛选项目权限，包括移动端 */
    let ProListsMenu = menusItem.project?.filter(project => isCoSuper || iuser.info.projects.find(item => item.id === project.project)) || [];
    ProListsMenu.forEach(node => {
      const isProSuper = iuser.admin_projects2.includes(node.project);
      node.children = getValidMenus(node?.children || [], isCoSuper || isProSuper, iuser.project_roles.filter(i => i.project_id === node.project));
    });
    ProListsMenu = ProListsMenu.filter(item => item.children.length);
    
    /* 存储所有有效菜单，包括移动端 */
    localMenusStore.setLocalMenus({ CoMenus, ProListsMenu });
    /* 登入判断 */
    
    const path1 = getToCompanyPath();
    if (path1) {
      router.push(path1);
      return;
    }
    
    const path2 = getToSomeProjectPath();
    if (path2) {
      router.push(path2);
    } else {
      ElMessage.error('暂无登入权限，请联系管理员');
    }
  }).catch(error => {
    loginResd.logining = false;
  });
}
const getProjectList = (iuser) => {
  return new Promise((resolve, reject) => {
    projectApi({
      method: 'get',
      params: {
        page: 1,
        ordering: "-dtime",
        used: true,
      },
    }).then(res => {
      resolve(res?.results || []);
    }).catch(e => {
      reject(e);
    });
  });
}
const getCompanyItems = (iuser) => {
  return new Promise((resolve, reject) => {
    companyByIdItems({
      method: 'get',
      id: iuser.info.company,
      params: {},
    }).then(res => {
      resolve(res);
    }).catch(e => {
      reject(e);
    });
  });
}
const getCompanyDetail = (iuser) => {
  return new Promise((resolve, reject) => {
    companyById({
      method: 'get',
      id: iuser.info.company,
      params: {},
    }).then(res => {
      resolve(res);
    }).catch(e => {
      reject(e);
    });
  });
}

const forgetClick = () => {
  Resd.forget = true;
  repasswordResd.phone = loginResd.username;
}

/* 忘记密码 */
const repasswordResd = reactive({
  phone: '',
  password: '',
  passwordType: true,
  passwordConfirm: '',
  code: '',
  count: 60,
  sendText: '获取验证码',
  logining: false,
});
let timer = null;
const sendCodeCheck = () => {
  if (!repasswordResd.phone) {
    ElMessage.error('请输入手机号');
    return;
  } else if (!isPhone(repasswordResd.phone)) {
    ElMessage.error('请验证手机号是否正确');
    return;
  } else if (repasswordResd.count > 0 && repasswordResd.count < 60) {
    return;
  }
  iuserPhonecode({
    method: 'post',
    data: {
      phone: repasswordResd.phone,
    },
  }).then(res => {
    if (!res) {
      return;
    }
    timeCounter();
    timer = setInterval(() => {
      timeCounter();
    }, 1000);
  });
}
const timeCounter = () => {
  repasswordResd.count --;
  if (repasswordResd.count === 0) {
    repasswordResd.sendText = '重新发送';
    repasswordResd.count = 60;
    clearInterval(timer);
  }
}
const confirmClick = () => {
  if (!isPhone(repasswordResd.phone)) {
    ElMessage.error('请验证手机号是否正确');
    return;
  } else if (!repasswordResd.code) {
    ElMessage.error('请输入短信验证码');
    return;
  } else if (!repasswordResd.password) {
    ElMessage.error('请输入密码');
    return;
  } else if (!repasswordResd.passwordConfirm) {
    ElMessage.error('请确认密码');
    return;
  } else if (repasswordResd.password !== repasswordResd.passwordConfirm) {
    ElMessage.error('密码不一致');
    return;
  }
  actionRepassword();
}
const actionRepassword = () => {
  repasswordResd.logining = true;
  const password = Md5.hashStr('.ieieye.com' + repasswordResd.password + 'shhengji');
  iuserRepassword({
    method: 'post',
    params: {
      phone: repasswordResd.username,
      code: repasswordResd.code,
      password: password,
    },
  }).then(res => {
    if (res) {
      return;
    }
    backloginClick()
  }).catch(() => {
    repasswordResd.logining = false;
  });
}
const backloginClick = () => {
  Resd.forget = false;
  loginResd.username = repasswordResd.phone;
}
</script>

<template>
  <div class="login">
    <Particles />
    
    <div class="info-boast flex-column">
      <div class="info-line1 flex--center">
        <p>您值得信赖的</p>
        <div class="blue-bg">控制智能化</div>
      </div>
      <strong>智慧运维云平台</strong>
      <p class="info-line3">——随时随地全局掌控！</p>
    </div>
    
    <div class="popup flex-column" v-if="Resd.forget">
      <div class="popup_name">找回密码</div>
      <div class="form-line">
        <el-input
          size="large"
          v-model="repasswordResd.phone"
          clearable
          name="username"
          prefix-icon="User"
          placeholder="请输入账号"
          @clear="repasswordResd.phone = ''; repasswordResd.password = ''; repasswordResd.passwordConfirm = ''; repasswordResd.code = '';"
        />
      </div>
      <div class="form-line flex--center">
        <el-input
          size="large"
          v-model="repasswordResd.code"
          prefix-icon="Lock"
          :maxlength="6"
          clearable
          placeholder="请输入验证码"
        />
        <el-button class="codeBox from-phone pointer" @click="sendCodeCheck()">
          {{ repasswordResd.count === 0 || repasswordResd.count === 60 ? repasswordResd.sendText : repasswordResd.count + 's' }}
        </el-button>
      </div>
      <div class="form-line">
        <el-input
          size="large"
          type="password"
          name="password"
          v-model="repasswordResd.password"
          prefix-icon="Lock"
          placeholder="请输入密码"
          show-password
        />
      </div>
      <div class="form-line">
        <el-input
          size="large"
          type="password"
          v-model="repasswordResd.passwordConfirm"
          prefix-icon="Lock"
          placeholder="请再次输入密码"
          show-password
        />
      </div>
      <button class="login-btn" :class="{'dis' : repasswordResd.logining}" @click="confirmClick()">
        {{ repasswordResd.logining ? '修改中...' : '修改'}}
      </button>
      <el-button link type="primary" @click="backloginClick()">返回登陆？</el-button>
    </div>
    
    <div class="popup flex-column" v-else>
      <div class="popup_name">欢迎回来</div>
      <div class="form-line">
        <el-input
          size="large"
          v-model="loginResd.username"
          prefix-icon="User"
          placeholder="请输入账号"
          clearable
          @clear="loginResd.username = ''; loginResd.password = ''; loginResd.code = '';"
        />
      </div>
      <div class="form-line">
        <el-input
          size="large"
          type="password"
          v-model="loginResd.password"
          prefix-icon="Lock"
          placeholder="请输入密码"
          show-password
        />
      </div>
      <div class="form-line flex">
        <el-input
          size="large"
          v-model="loginResd.code"
          :maxlength="4"
          :prefix-icon="SafetyIcon"
          clearable
          placeholder="请输入验证码"
        />
        <div class="codeBox">
          <PicCode @change="compareCodeChange"/>
        </div>
      </div>
      <button class="login-btn" :class="{'dis' : loginResd.logining}" @click="loginClick()">
        {{ loginResd.logining ? '登录中...' : '登录'}}
      </button>
      <el-button link type="primary" @click="forgetClick()">忘记密码？</el-button>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.login {
  width: 100%;
  height: 100%;
  background: url('@T2/assets/login-bg.png') no-repeat center;
  background-size: 100% 100%;
}
.info-boast {
  position: absolute;
  left: 9.6%;
  top: 15.27%;
  .info-line1 {
    font-weight: 400;
    height: 64px;
    p {
      font-size: 46px;
      color: #43464D;
      margin-right: 20px;
    }
    .blue-bg {
      width: 120px;
      height: 34px;
      line-height: 34px;
      text-align: center;
      font-size: 16px;
      color: #FFFFFF;
      background: #0079FE;
      border-radius: 20px 0px 20px 0px;
    }
  }
  strong {
    font-weight: 500;
    font-size: 70px;
    color: #43464D;
    height: 98px;
    line-height: 98px;
  }
  .info-line3 {
    margin-top: 16px;
    font-weight: 400;
    font-size: 24px;
    color: #43464D;
  }
}
.popup {
  position: absolute;
  right: 12.34%;
  top: 50%;
  width: 500px;
  padding: 40px;
  transform: translateY(-50%);
  background: #FFFFFF;
  box-shadow: 0px 4px 20px 0px rgba(134,175,255,0.25);
  border-radius: 8px;
  .popup_name {
    height: 36px;
    line-height: 36px;
    font-weight: 600;
    font-size: 26px;
    color: #111111;
    text-align: center;
    letter-spacing: 2px;
    margin-bottom: 38px;
  }
  .form-line {
    width: 100%;
    margin: 12px 0;
    .codeBox {
      margin-left: 10px;
      width: 130px;
      height: 42px;
      line-height: 42px;
    }
  }
  .login-btn {
    margin: 38px 0 24px;
    height: 42px;
    line-height: 42px;
    text-align: center;
    background: #0079FE;
    border-radius: 4px;
    font-size: 16px;
    font-weight: 400;
    letter-spacing: 2px;
    color: #FFFFFF;
    border: none;
    cursor: pointer;
    &.dis {
      background: #0079FE;
      opacity: .85;
    }
  }
  .el-button {
    margin-left: auto;
  }
}
</style>

<style scoped>
:deep(input:-webkit-autofill),
:deep(input:-webkit-autofill:hover),
:deep(input:-webkit-autofill:focus) {
  -webkit-box-shadow: 0 0 0 1000px #FFFFFF inset !important;
  box-shadow: 0 0 0 1000px #FFFFFF inset !important;
  background-color: #FFFFFF !important;
  background-image: none !important;
  -webkit-text-fill-color: #606266 !important;
}
:deep(.el-input--large .el-input__wrapper) {
  padding: 2px 15px;/* 原本值为 1px 15px;但是自动填充时，仔细观察发现内容区域遮住了部分shadow导致有一点点不美观 */
}
</style>